package com.atguigu.crowd.handle;

import com.atguigu.crowd.api.MySQLReomteService;
import com.atguigu.crowd.api.RedisRemoteService;
import com.atguigu.crowd.config.ShowMessageProperties;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.vo.MemberLoginVo;
import com.atguigu.crowd.entity.vo.MemberVO;
import com.atguigu.crowd.constant.CrowdConstan;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author zzqstart
 * @Description
 * @date 2022-09-17 14:27
 */
@Controller
public class MemberHandle {
    @Autowired
    private ShowMessageProperties showMessageProperties;
    @Autowired
    private RedisRemoteService redisRemoteService;
    @Autowired
    private MySQLReomteService mySQLReomteService;

    @RequestMapping("/auth/member/do/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:http://localhost";
    }

    /**
     * @Description 用户登录
     *
     * @Author zzqstart
     * @Date 2022/9/19 13:15
     * @Param [loginacct, userpswd, model, session]
     * @return java.lang.String
     **/
    @RequestMapping("/auth/member/do/login")
    public String login(@RequestParam("loginacct")String loginacct,
                        @RequestParam("userpswd") String userpswd,
                        Model model,
                        HttpSession session
                        ){
        // 通过账号查询密码
        ResultEntity<MemberVO> accountResultEntity = mySQLReomteService.getMemberPOByLoginAcctRemote(loginacct);
        if (ResultEntity.FALIED.equals(accountResultEntity.getResult())){
            model.addAttribute(CrowdConstan.ATTR_NAME_MEMBER_LOGIN_FAILED,accountResultEntity.getMessage());
            return "member-login";
        }

        // 账号是否存在
        MemberVO data = accountResultEntity.getData();
        if (data == null){
            model.addAttribute(CrowdConstan.ATTR_NAME_MEMBER_LOGIN_FAILED,CrowdConstan.MESSAGE_LOGIN_FAILED);
            return "member-login";
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String userpswdDB = accountResultEntity.getData().getUserpswd();
        if (!passwordEncoder.matches(userpswd,userpswdDB)){
            model.addAttribute(CrowdConstan.ATTR_NAME_MEMBER_LOGIN_FAILED,CrowdConstan.MESSAGE_LOGIN_FAILED);
            return "member-login";
        }

        MemberLoginVo memberLoginVo = new MemberLoginVo(data.getId(), data.getUsername(), data.getEmail());


        session.setAttribute(CrowdConstan.ATTR_NAME_LOGIN_MEMBER,memberLoginVo);

        return "redirect:http://localhost/auth/member/to/center/page";
    }

    /**
     * @Description 注册
     *
     * @Author zzqstart
     * @Date 2022/9/19 13:15
     * @Param [memberVO, model]
     * @return java.lang.String
     **/
    @RequestMapping("/auth/member/do/regist")
    public String regist(MemberVO memberVO, Model model){
        // 1、比对验证码
        // 用户手机号在redis中对应的key
        String redisKey = CrowdConstan.REDIS_COOE_PREFIX + memberVO.getPhoneNum();
        // redis中的验证码
        ResultEntity<String> redisResultEntity = redisRemoteService.getRedisStringValueByKeyRemote(redisKey);
        if (ResultEntity.FALIED.equals(redisResultEntity.getResult())){
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE,redisResultEntity.getMessage());
            return "member-reg";
        }

        // redis中的验证码
        String redisCode = redisResultEntity.getData();
        if (redisCode == null){
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE,"验证码已过期");
            return "member-reg";
        }

        // 用户输入的验证码
        String currentCode = memberVO.getCode();

        if (!Objects.equals(currentCode,redisCode)){
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE,"验证码错误");
            return "member-reg";
        }
        // 删除redis中的验证码
        redisRemoteService.removeRedisKeyRemote(redisKey);


        // 2、存入注册信息存入数据库
        // ①密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String userpswd = memberVO.getUserpswd();
        userpswd = passwordEncoder.encode(userpswd);
        MemberVO memberVOEncrypt = new MemberVO();
        BeanUtils.copyProperties(memberVO,memberVOEncrypt);
        memberVOEncrypt.setUserpswd(userpswd);

        // ②将membervo转为memberpo
        MemberPO memberPO = new MemberPO();
        BeanUtils.copyProperties(memberVOEncrypt,memberPO);
        // 3、保存
        ResultEntity<String> saveResultEntity = mySQLReomteService.saveMemberpoToRegistAcctRemote(memberPO);

        // 4、是否保存成功
        // todo 返回异常instanceof
        if (ResultEntity.FALIED.equals(saveResultEntity.getResult())){
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE,saveResultEntity.getMessage());
            return "member-reg";
        }
        return "redirect:http://localhost/auth/member/to/login/page";
    }

    /**
     * @Description 发送短信
     *
     * @Author zzqstart
     * @Date 2022/9/19 13:14
     * @Param [phoneNum]
     * @return com.atguigu.crowd.util.ResultEntity<java.lang.String>
     **/
    @ResponseBody
    @RequestMapping("/auth/member/send/short/message.json")
    public ResultEntity<String> authMemberSendShortMessage(@RequestParam("phoneNum") String phoneNum){
       ResultEntity<String> setMessageResultEntity = CrowdUtil.SendShortMessage(
                showMessageProperties.getHost(),
                showMessageProperties.getPath(),
                showMessageProperties.getMethod(),
                showMessageProperties.getAppcode(),
                phoneNum,
                showMessageProperties.getTemplateId()
        );

        // 是否发送成功
        if (ResultEntity.SUCCESS.equals(setMessageResultEntity.getResult())){
            // 存入redis的key
            String key = CrowdConstan.REDIS_COOE_PREFIX + phoneNum;
            // 验证码存入redis
            String code = setMessageResultEntity.getData();

            ResultEntity<String> redisResultEntity = redisRemoteService.setRedisKeyValueRemoteWithTimeout(key, code, 5, TimeUnit.MINUTES);

            // 是否成功存入redis
            if (ResultEntity.SUCCESS.equals(redisResultEntity.getResult())){
                return ResultEntity.successWithoutData();
            }

            return redisResultEntity;
        }else {
            return setMessageResultEntity;
        }
    }


}
